package com.itheima.youdianda.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.dto.SysRoleDto;
import com.itheima.youdianda.entity.SysRole;
import com.itheima.youdianda.entity.SysRoleMenu;
import com.itheima.youdianda.mapper.SysRoleMapper;
import com.itheima.youdianda.service.SysRoleMenuService;
import com.itheima.youdianda.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 角色添加
     * @param sysRoleDto
     */
    @Override
    @Transactional //事务管理(保证对两张表的操作均成功,以保证数据的一致性)
    public void saveWithMenu(SysRoleDto sysRoleDto) {
        //保存角色的基本信息到角色表(sys_role)
        this.save(sysRoleDto);
        //获取角色id,一起封装到角色菜单表(sys_role_menu)
        String roleId = sysRoleDto.getId();
        //获取角色菜单
        List<SysRoleMenu> roleMenus = sysRoleDto.getRoleMenus();
        roleMenus = roleMenus.stream().map(item -> {
            item.setRole_id(roleId);
            return item;
        }).collect(Collectors.toList());
        //将角色菜单信息存储(添加)到角色菜单表(sys_role_menu)
        //saveBatch():批量添加
        sysRoleMenuService.saveBatch(roleMenus);
    }
}
